package jxau.xn.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.junit.Test;

import com.sun.org.apache.commons.digester.rss.Item;

public class FileUpload extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
            this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
           DiskFileItemFactory factory=new DiskFileItemFactory();
           ServletFileUpload sfu = new ServletFileUpload(factory);
           byte[] b = new byte[500];
           try {
			List<FileItem> items = sfu.parseRequest(request);
		    for(FileItem item :items){
		    	 if(item.isFormField()){
		    		 System.out.println(item.getName()+":"+item.getString());
		    	 }else{
		    		 String path = this.getServletContext().getRealPath("/upload");
		    		 System.out.println(path);
		    		 String endFile = item.getName();
		    		 String filepath = path+"\\"+endFile;
		    		 System.out.println(filepath);
		    		 File file = new File(filepath);
		    		 if(!file.exists()) file.createNewFile();
		    		 InputStream is = item.getInputStream();
		    		 FileOutputStream fos = new FileOutputStream(file);
		    		 int i=0;
		    		 while((i = is.read(b))!=-1){
		    			 fos.write(b);
		    		 }
		    		 is.close();
		    		 fos.close();
		    	 }
		    }
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
